'''
It is need to build some scripts to invoke remote client to connect the server
To test the resource requirement for 7 AI players with increasing number(1 to 4)  of the Speculator players who doesnt play just watch.
This is only a local test, need to improve it to invoke remotely clients
'''
import Process,os, sys, time,DB, Analysis,shutil
from Configuration import Configuration
from Performance import Performance
def server(speculator, expId, turn):
    Configuration.initExp("1c")
    Configuration.set("game_creation", "map_x", 10)
    Configuration.set("game_creation", "map_y", 10)
    Configuration.set("difficulty", "max_no_competitors", 8)
    Configuration.set("network", "max_companies", 8 + speculator)
    if sys.platform == "win32":
        os.system("server.bat")#start a 8 AI games
    elif sys.platform.find("linux") >= 0: 
        os.system("openttd -D&")
    print "server start"
    for i in xrange(0,speculator/1):
        """the Server can't handle simulatively multiple connections"""
        time.sleep(5)
        startClient(clientIP[i], expId, turn, speculator)
        
clientIP = ["192.168.0.100", "192.168.0.100", "192.168.0.100", "192.168.0.100"]

def getServerIP():
    return "192.168.0.1"

def startClient(clientIP, expId, turn, factor):
    serverIP = getServerIP()
    cmd = "ssh -i ~/.ssh/sqid -l sq " + clientIP + " 'export DISPLAY=\":0\"; cd OpenTTDTesting; cd src; nohup ./client.sh " + serverIP + " %d"%expId
    cmd = cmd + " %d"%turn + " %d"%factor + " %d"%Process.maxYear + " " + clientIP + "&' &\r\n"
    if sys.platform == "win32":
        path = "c:\\cygwin\\home\\Q\\startClient.sh"
        f = open(path, "w")
        print >> f, cmd
        f.close()
        print cmd
    os.system("startClient.bat")
#    os.system(cmd)
    print "start client yet"
    return True


def copyFile(expId, factor):
    for i in xrange(0, factor/1):
        copyFileFromClient(clientIP[i], expId)

def copyFileFromClient(clientIp, expId):
#   There are some error in Cygwin, It don't read my script correct 
    cmd = "scp -i ~/.ssh/sqid -r sq@"+clientIp + ":~/OpenTTDTesting/test_result/1c/analysis/%d"%expId + "* ~/file/"
    if sys.platform == "win32":
        path = "c:\\cygwin\\home\\Q\\startClient.sh"
        f = open(path, "w")
        print >> f, cmd
        f.close()
        print cmd
        os.system("startClient.bat")
    src = "c:/cygwin/home/Q/file"
    dest = os.path.join("..", "test_result", "1c", "analysis","client")
    dest2 = os.path.join("..", "test_result", "trunk")
    for file in os.listdir(src):
        source = src + "/" + file
        shutil.copy(source, dest)
        shutil.copy(source, dest2)

if __name__ == "__main__":
    print "server"
    expName = "1c"
    path = os.path.join("..","test_result")
    Configuration.mkExpDir(expName)
    f = open(os.path.join(path, "networkName"),"a")
    measurement = Performance()
    measurement.flag = 1
    measurement.start()
    log = open(os.path.join(path, "log"),"a")
    Configuration.increaseId()
    expId = Configuration.getId()
    totoalTurn = 10
    Process.maxYear = 1
    selfIP = "192.168.0.1"
    maxSpeculator = 1
    Analysis.updateSkipList(Process.maxYear)
    for turn in xrange(1, totoalTurn + 1/1):
        for factor in xrange(1, maxSpeculator+1/1):
            print >> log, "1c_client"    
            print >>log,"turn%d"%turn, factor
            filename = "test1c" + "_result_"+"%d"%turn+"_%d"%factor +".txt"
            file = open(os.path.join(path, expName, filename), "w")
            starttime = time.time()
            print >> file, "-----------" + time.asctime() + "-----------\n" + "%f"%starttime
            print >> file, "%d_"%turn+ " clients %d"%factor
    
            server(factor, expId, turn)
            
            Process.killOpenTTD(file)
            endtime = time.time()
            print >> file,"%f"%endtime + "\n-----------" + time.asctime() + "-----------\n"
            print >> log,"%f"%endtime + "\n-----------" + time.asctime() + "-----------\n"
            file.flush()
            savefilename = "%d"%expId + "_" + expName + "_%d"%turn + "_%d_"%factor + selfIP
            DB.type = 2
            DB.insert(expId, expName, turn, factor, starttime, endtime, -1.0, Process.maxYear, savefilename)
            measurement.save()
            Analysis.analysisCPUandMemSingleFile(expId, expName, turn, factor, filename, savefilename + "_cpu.txt")
            time.sleep(5)
            copyFile(expId, factor)
